<?php

namespace maotool\core\serializer\closure;

class SerializableClosure
{

    /**
     * @var ClosureParser
     */
    private $instance;


    public function __construct($closure)
    {
        $closureParser = ClosureParser::fromCallable($closure);
        $this->instance = [
            "parameters" => $closureParser->getParameters(),
            "body" => $closureParser->getBody(),
            "context" => $closureParser->getContext(),
            "code" => $closureParser->getCode(),
            "name" => $closureParser->getName(),
            "class" => $closureParser->getClass(),
        ];
    }

    public function getClosure()
    {
        $closure = function () {};
        $scripts = [];
        foreach ($this->instance["context"] as $key => $value) {
            $scripts[] = "\$$key = unserialize(\"" . serialize($value) . "\");\n";
        }
        $scripts[] = "\$closure = ";
        $scripts[] = $this->instance["code"];
        $scripts[] = ";";
        $script = implode($scripts);
        eval($script);
        return $closure;
    }

}